package abel.wlmr.model.type;

import abel.wlmr.model.WlmrUserData;
import abel.wlmr.model.WlmrException;
import io.netty.buffer.ByteBuf;

/**
 * B.4.3.4.4.1 数据单元标识定义
 * 数据单元标识由信息点标识 DA 和信息类标识 DT 组成，表示信息点和信息类型，格式见图 B.7。
 * 信息点 DA
 * DA1 D7 D6 D5 D4 D3 D2 D1 D0
 * DA2 D7 D6 D5 D4 D3 D2 D1 D0
 * 信息类 DT
 * DT1 D7 D6 D5 D4 D3 D2 D1 D0
 * DT2 D7 D6 D5 D4 D3 D2 D1 D0
 * 
 * @author Abel
 *
 */
public class DataIdBody extends WlmrUserData {

    public static final short FIXED_LEN = 4;

    private DataAddrField da;

    private DataTypeField dt;

    public DataIdBody() {
        super((short) 4);

        da = new DataAddrField();
        dt = new DataTypeField();
    }

    @Override
    public ByteBuf appendBuf(ByteBuf buf) {
        buf.writeShortLE(da.getValue());
        buf.writeShortLE(dt.getValue());

        return buf;
    }

    @Override
    public int parseBuf(ByteBuf buf) throws WlmrException {
        if (buf.readableBytes() < getGuessedLength()) {
            return -1;
        }

        da = new DataAddrField();
        da.parseValue(buf.readShortLE());

        dt = new DataTypeField();
        dt.parseValue(buf.readShortLE());

        return 4;
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.WlmrDataPart#getFinalLen()
     */
    @Override
    public short getFinalLen() {
        return FIXED_LEN;
    }

    /* (non-Javadoc)
     * @see abel.wlmr.model.WlmrDataPart#getMinLength()
     */
    @Override
    public int getMinLength() {
        return FIXED_LEN;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return String.format("{da:%s, dt:%s}", da, dt);
    }

    /**
     * @return the da
     */
    public DataAddrField getDa() {
        return da;
    }

    /**
     * @param da
     *            the da to set
     */
    public void setDa(DataAddrField da) {
        this.da = da;
    }

    /**
     * @return the dt
     */
    public DataTypeField getDt() {
        return dt;
    }

    /**
     * @param dt
     *            the dt to set
     */
    public void setDt(DataTypeField dt) {
        this.dt = dt;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof DataIdBody)) {
            return false;
        }

        DataIdBody id = (DataIdBody) obj;

        // do not compare if any of fields is null.
        if (this.da == null || this.dt == null || id.da == null || id.dt == null) {
            return false;
        }

        return da.equals(id.da) && dt.equals(id.dt);
    }
}
